///-----------------------------------------------------------------------------
/// Filename: TextController.cs
///
/// Description: 
/// Controller that sends a text response.
///
/// History:
/// 06 Apr 2005	Aaron Clauson	Created.
/// 
/// License: 
/// Public Domain.
///-----------------------------------------------------------------------------

using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using MaverickLite.Config;
using MaverickLite.Model;
using MaverickLite.Security;
using MaverickLite.View;
using log4net;

namespace MaverickLite.Controller
{
	public class TextController : ControllerProduct
	{
		private const string TEXT_CONTENT_TYPE = "text/text";

		protected string m_contentType = TEXT_CONTENT_TYPE;
		protected string m_output = null;
		protected AuthenticationResult m_authResult;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="initParams">The xml element containing the controller's intial parameters.</param>
		public TextController(XmlElement initParams)
		{			
			try
			{	
				//logger.Debug("TextController created.");

				// Clone the node containing the initial controller parameters, just in case
				// a derived controller wants to check or do some custom processing.
				InitialParameters = (XmlElement)initParams.Clone();

				#region Extract the childless node parameters into the simple parameters hashtable.

				// Load all the simple parameter nodes - those without children - into a hashtable.
				foreach(XmlNode parameterNode in initParams.SelectNodes(CONTROLLER_PARAM_KEY))
				{
					// Check if this is a childless (aka simple) parameter.
					if(parameterNode.ChildNodes.Count == 0)
					{
						string parameterName = parameterNode.Attributes.GetNamedItem(CONTROLLER_PARAM_NAME_ATTRIBUTE).Value;
						string parameterValue = parameterNode.Attributes.GetNamedItem(CONTROLLER_PARAM_VALUE_ATTRIBUTE).Value;

						// Insert name value pair into the parameters hashtable.
						if(parameterName != null && parameterName.Trim() != String.Empty)
						{
							this.SimpleParameters.Add(parameterName, parameterValue);
						}
					}		
				}

				#endregion
			}
			catch(Exception excp)
			{
				throw new ApplicationException("Exception TextController: " + excp.Message);
			}
		}

		
		public override void Go(HttpContext context)
		{
			base.Go(context);

			AuthenticationController authenticationController = new AuthenticationController();
			m_authResult = authenticationController.Authenticate(this.SimpleParameters, this.MavRequestState, this.MavSessionState);

			if(!m_authResult.Authenticated)
			{
				//throw new HttpException(401, "Please login in order to access this page.");
				context.Response.Redirect("login.aspx", true);
			}
		}

		public void Finish(HttpContext context)
		{
			// Don't use this header it breaks IE!
			//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

			context.Response.ContentType = m_contentType;
			//context.Response.ContentType = "text/csv";
				
			// Write the output to the response stream without a view stage.
			//StreamWriter finalStageWriter = new StreamWriter(context.Response.OutputStream, Encoding.UTF8);
		
			//finalStageWriter.Write(m_output);
			//finalStageWriter.Flush();

			//context.Response.AppendHeader("Content-Disposition", "inline;filename=filename.csv");

			context.Response.WriteFile(@"c:\temp\addressx.csv");

			context.Response.End();
		}

		protected void Redirect(HttpContext context, string redirectPath)
		{
			logger.Debug("The Controller specified a client redirect to " + redirectPath + ".");
			
			foreach(DictionaryEntry specialParameter in m_specialParameters)
			{
				redirectPath = Regex.Replace(redirectPath, Regex.Escape((string)specialParameter.Key), (string)specialParameter.Value);
			}
			
			context.Response.Redirect(redirectPath, true);
		}
	}
}
